var TBody = Backbone.View.extend({
	tagName : "tbody",
	initialize : function() {
		this.render();
		this.model.on("change", this.render, this);
	},
	render : function() {
		var html = _.template($("#rows_template").html(), this.model.toJSON());
		if(this.model.get('data').length > 0){
			this.body = $(html);
			this.$el.html(this.body);
						
		}
		else this.$el.html(this.options.empty);

	}
});

var Table = Backbone.View.extend({
	initialize : function() {
		this.render();
	},

	render : function() {
		var html = _.template($("#table_template").html(), this.options.head, {variable: "headers"});
		this.table = $(html);
		this.$el.html(this.table);
		this.heads = $('thead th', this.$el).first();
		var data = this.model.get('data');
		var t = this;
		this.heads.toggle(      
	  function () {
        t.buildPager(
        	_.sortBy(data, function(arr){
        		return arr[0].toUpperCase();
        	})
        );
        $(this).css({"color":"green"});
      },
      function () {
        t.buildPager(
        	_.sortBy(data, function(arr){
        		return arr[0].toUpperCase();
        	}).reverse()
        );
        $(this).css({"color":"red"});
      },
      function () {
      	t.buildPager(data);
        $(this).css({"color":"black"});
      });
		// this.dataModel = new ItemModel(this.model.get('data'));
		this.empty = $('tbody tr', this.table);
		this.bodyModel = new ItemModel({data:[[]]});
		this.body = new TBody({
			el : $('tbody', this.$el),
			empty: this.empty,
			model : this.bodyModel
		});
		this.pager = $("<div></div>")
		this.$el.append(this.pager);		
				
		this.buildPager(data);
	},
	buildPager: function(data){
		this.pager.pagination(
			ViewData.root.table.get('data').length,
			{
		        items_per_page:5,
		        num_edge_entries : 2,
		        num_display_entries:5,
		        load_first_page:true,
		        callback:this.pageCallback,
		        data: data,
		        model: this.bodyModel
	        }
		);		
	},
	pageCallback: function(cur, root){
		// if(root.parent().length ==0 )
			// return false;
		var p = this.items_per_page,
			start = cur * p,
			end = Math.min((cur+1)*p, this.count),
			data = this.data.slice(start, end);
			this.model.set('data', data);
		return false;
	}	
}); 